package com.hxgz.steel.controller.portal;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hxgz.steel.common.Const;
import com.hxgz.steel.common.ResponseCode;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.domain.Page;
import com.hxgz.steel.domain.Product;
import com.hxgz.steel.domain.ProductWithBLOBs;
import com.hxgz.steel.domain.User;
import com.hxgz.steel.dto.ExtendGoodDto;
import com.hxgz.steel.dto.GoodDto;
import com.hxgz.steel.dto.GoodSelectDto;
import com.hxgz.steel.dto.ProductInsertDto;
import com.hxgz.steel.service.GoodsManageService;
import com.hxgz.steel.util.ExtractStringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author liuhuan
 * @description  商品管理
 * @date 2019/1/22
 */
@RestController
@RequestMapping("goodsManage")
@Api(tags = "GoodsManageController",description = "前台-卖家中心-商品管理")
public class GoodsManageController {

    @Autowired
    GoodsManageService service;

    @ApiOperation(value = "商品管理-页面",notes = "metrails 材质；spec 规格")
    @RequestMapping(value ="init.do",method = RequestMethod.POST)
    public ServerResponse<Map<String,Object>> init(HttpServletRequest httpServletRequest,@ApiParam("1-风类(\"default\")  2-水类  3-电类  4-消防类") Integer id){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return service.init(id);
    }

    /**
     * 商品列表
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value="listGoods.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-商品列表")
    public ServerResponse<ExtendGoodDto> listGoods(HttpServletRequest httpServletRequest, GoodSelectDto selectDto, Page page){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        GoodDto dto = new GoodDto();
        dto.setUserId(user.getId());
        dto.setStatus(selectDto.getStatus());
        dto.setUpdateTimeStr(selectDto.getStartDate());
        dto.setUpdateTimeEnd(selectDto.getEndDate());
        dto.setMaterials(selectDto.getMaterials());
        dto.setCategoryId(selectDto.getCategoryId());
        dto.setProductName(selectDto.getProductName());
        dto.setTopName(selectDto.getTopName());
        dto.setFeatures(selectDto.getFeatures());
        //TODO page默认值
        if(!"id desc".equalsIgnoreCase(page.getOrderBy())){
            dto.setSort(page.getOrderBy());
        }
        dto.setTopNameId(selectDto.getTopNameId());
        dto.setNameId(selectDto.getNameId());
        dto.setMaterialsId(selectDto.getMaterialsId());
        dto.setFeaturesId(selectDto.getFeaturesId());
        return service.listGoods(dto,page);
    }

    /**
     * 查询商品明细
     * @param id
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value="selectProductInfo.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-商品明细")
    public ServerResponse<Map<String,Object>> selectProductInfo(@RequestParam(required = true)@ApiParam(value = "1-风类  2-水类  3-电类  4-消防类")Integer categoryId , @RequestParam(required = true) Long id, HttpServletRequest httpServletRequest){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        Product occasionProduct = new Product();
        occasionProduct.setId(id);
        occasionProduct.setUserId(user.getId());
        occasionProduct.setCategoryId(categoryId);
        return service.selectProductInfo(occasionProduct);
    }

    @RequestMapping(value="insertPage.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-新增/编辑商品页面")
    public ServerResponse insertPage(HttpServletRequest httpServletRequest,@ApiParam("1-风类(\"default\")  2-水类  3-电类  4-消防类")Integer id){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return service.insertPage(id);
    }

    /**
     * 新增商品
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value="insertProduct.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-新增/编辑商品")
    public ServerResponse insertProduct(HttpServletRequest httpServletRequest, ProductInsertDto pInsertDto,
                                        @RequestParam(required = true)@ApiParam("[{ \"color\": \"黑色\", \"model\": \"0.55mm\", \"price\": \"15.00\" }, { \"color\": \"黑色\", \"model\": \"0.55mm\", \"price\": \"15.00\" }]") String productModel,
                                        @RequestParam(required = true)@ApiParam("[{\"name\":\"名称\",\"info\":\"PVV护套软线\"},{\"name\":\"型号\",\"info\":\"PVV2*0.5/0.75/1/1.5/2.5/4\"},{\"name\":\"规格\",\"info\":\"2*0.5/0.75/1/1.5/2.5/4\"}]") String productParameter){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        JSONArray jarray = JSONArray.parseArray(productModel);
        for (int i = 0; i < jarray.size(); i++) {
            JSONObject job = jarray.getJSONObject(i);
            String str = job.getString("price");
            if (!ExtractStringUtils.isNumStr(str)){
                return ServerResponse.createByErrorMessage("参数格式错误");
            }
        }
        ProductWithBLOBs product = new ProductWithBLOBs();
        product.setUserId(user.getId());
        product.setId(pInsertDto.getId());
        product.setCategoryId(pInsertDto.getCategoryId());

        product.setName(pInsertDto.getName());
        product.setMaterials(pInsertDto.getMaterials());
        product.setMainImage(pInsertDto.getSubImages().split(";")[0]);
        product.setSubImages(pInsertDto.getSubImages());
        product.setStock(pInsertDto.getStock());
        product.setStatus(0);//未上架
        product.setProductCode(pInsertDto.getProductCode());
        if (pInsertDto.getTaxPoint() == null) {
            product.setTaxPoint(new BigDecimal(0));
        }else {
            product.setTaxPoint(pInsertDto.getTaxPoint());
        }
        product.setFeatures(pInsertDto.getFeatures());
        product.setSubtitle(pInsertDto.getSubtitle());
        product.setDetail(pInsertDto.getDetail());
        product.setFreight(pInsertDto.getFreight());
        product.setFreightStatus(pInsertDto.getFreightStatus());
        product.setTopName(pInsertDto.getTopName());
        product.setTopNameId(pInsertDto.getTopNameId());
        product.setFeaturesId(pInsertDto.getFeaturesId());
        product.setMaterialsId(pInsertDto.getMaterialsId());
        product.setNameId(pInsertDto.getNameId());
        product.setUnit(pInsertDto.getUnit());
        return service.insertProduct(product,productModel,productParameter);
    }

    /**
     * 商品（批量）上架
     * @param httpServletRequest
     * * @param  ids 选中的id
     * @return
     */
    @RequestMapping(value="grounding.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-商品（批量）上架")
    public ServerResponse grounding(HttpServletRequest httpServletRequest,@RequestParam @ApiParam(value = "选中多个的id",required = true)String ids){
            User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        if ("".equals(ids)){
            return ServerResponse.createByErrorMessage("没有选中商品");
        }
        return service.updateStatusByUserIdAndId(user.getId(), ids,1);
    }

    /**
     * 商品（批量）下架
     * @param httpServletRequest
     * @param  ids 选中的id
     * @return
     */
    @RequestMapping(value="undercarriage.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-商品（批量）下架")
    public ServerResponse undercarriage(HttpServletRequest httpServletRequest,@RequestParam @ApiParam(value = "选中多个的id",required = true)String ids){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        if ("".equals(ids)){
            return ServerResponse.createByErrorMessage("没有选中商品");
        }
        return service.updateStatusByUserIdAndId(user.getId(),ids,2);
    }

    /**
     * 商品（批量）删除
     * @param httpServletRequest
     * * @param  ids 选中的id
     * @return
     */
    @RequestMapping(value="delete.do",method = RequestMethod.POST)
    @ApiOperation("商品管理-商品（批量）删除")
    public ServerResponse delete(HttpServletRequest httpServletRequest, @RequestParam @ApiParam(value = "选中多个的id",required = true)String ids){
        User user = Const.checkUserLogin(httpServletRequest);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        if ("".equals(ids)){
            return ServerResponse.createByErrorMessage("没有选中商品");
        }
        return service.updateStatusByUserIdAndId(user.getId(), ids,3);
    }
}
